package org.sshtunnel;

import java.io.IOException;

import com.trilead.ssh2.Connection;

import android.util.Log;

public class SSHServer implements Runnable {

	private static final String TAG = "SSHServer";
	private final static int AUTH_TRIES = 2;

	private Connection connection;
	private String user;
	private String password;
	private boolean connected = false;
	
	private ConnectionHandler connectionHandler = null;
	
	public SSHServer(Connection connection, String user, String password,
			ConnectionHandler connectionHandler) {
		super();
		this.connection = connection;
		this.user = user;
		this.password = password;
		this.connectionHandler = connectionHandler;
	}

	private void authenticate() {
		try {
			if (connection.authenticateWithNone(user)) {
				return;
			}
		} catch (Exception e) {
			Log.d(TAG, "Host does not support 'none' authentication.");
		}

		try {

			if (connection.authenticateWithPassword(user, password))
				return;

		} catch (IllegalStateException e) {
			Log.e(TAG,
					"Connection went away while we were trying to authenticate",
					e);

		} catch (Exception e) {
			Log.e(TAG, "Problem during handleAuthentication()", e);
		}
	}
	
	@Override
	public void run() {
		
		try {
			connection.setTCPNoDelay(true);
			connection.setCompression(true);
		} catch (IOException e) {
			Log.e(TAG, "Could not enable compression!", e);
			connectionHandler.handleFunc(false);
		}

		try {
			/*
			 * Uncomment when debugging SSH protocol:
			 */

			/*
			 * DebugLogger logger = new DebugLogger() {
			 * 
			 * public void log(int level, String className, String message) {
			 * Log.d("SSH", message); }
			 * 
			 * };
			 * 
			 * Logger.enabled = true; Logger.logger = logger;
			 */

			connection.connect(null, 30 * 1000, 30 * 1000);
			connected = true;

		} catch (Exception e) {
			Log.e(TAG,
					"Problem in SSH connection thread during connection", e);

			// Display the reason in the text.

			connectionHandler.handleFunc(false);
			return;
		}

		try {
			// enter a loop to keep trying until authentication
			int tries = 0;
			while (connected && !connection.isAuthenticationComplete()
					&& tries++ < AUTH_TRIES) {
				authenticate();

				// sleep to make sure we dont kill system
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			Log.e(TAG,
					"Problem in SSH connection thread during authentication", e);
			connectionHandler.handleFunc(false);
			return;
		}
		if (connected && connection.isAuthenticationComplete())
			connectionHandler.handleFunc(true);
		else
			connectionHandler.handleFunc(false);

	}

}
